package com.cpd.blog.service.impl;

import com.cpd.blog.common.constant.StatusCode;
import com.cpd.blog.common.utils.CheckUtil;
import com.cpd.blog.common.utils.CurrentUser;
import com.cpd.blog.common.utils.GenerateUtil;
import com.cpd.blog.common.utils.QiniuUtils;
import com.cpd.blog.dto.Result;
import com.cpd.blog.dto.User.UserVo;
import com.cpd.blog.service.UploadService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author: Copydown
 * @Date: 2022/05/21/15:48
 */
@Service
@RequiredArgsConstructor
public class UploadServiceImpl implements UploadService {

    private final QiniuUtils qiniuUtils;

    @Value("${qiniu.bucketUrl}")
    private String bucketUrl;

    @Override
    public Result uploadImg(MultipartFile file) {

        UserVo userVo = CurrentUser.get();

        if (CheckUtil.isNull(userVo)) {
            return Result.fail(StatusCode.USER_NOT_LOGIN);
        }

        String originalFilename = file.getOriginalFilename();

        //TODO：用 userId 做文件名不好，后期需引入mongoDB
        String filename = userVo.getId() + "_" + GenerateUtil.genUuidSize6() + "_" + originalFilename;

        boolean upload = qiniuUtils.upload(file, filename);
        if (upload) {
            return Result.success(bucketUrl + filename);
        }
        return Result.fail(StatusCode.IMAGE_UPLOAD_FAILED);
    }
}
